import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {Storage} from '@ionic/storage';
import {AppConfig} from '../common/app-config.enum';
import {ToastController} from '@ionic/angular';

@Injectable({
  providedIn: 'root'
})
export class RechargeGuard implements CanActivate {

  constructor(
    private storage: Storage,
    private toastCtrl: ToastController,
  ) {
  }

  async canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Promise<boolean> {
    const userInfo = await this.storage.get(AppConfig.USER_INFO);
    if (userInfo && userInfo[AppConfig.USER_TYPE_KEY] === 1) {
      return true;
    } else {
      this.showToast('企业用户无法在移动端充值');
      return false;
    }
  }

  // 显示通知消息
  private async showToast(msg) {
    const toast = await this.toastCtrl.create({
      message: msg || '请求数据失败',
      position: AppConfig.TOAST_POSITION,
      duration: AppConfig.TOAST_DURATION * 1
    });
    return toast.present();
  }
}
